import Mock from 'mockjs'

import { roleMock } from './modules/role.ts'
import { loginMock } from "./modules/login"
import { ResponseData } from 'constants/index.ts'
import { decodeToken } from './modules/utils.ts'

const mockList = [...roleMock, ...loginMock]

// 白名单
const whiteList = ["/mock/auth/login"]

mockList.forEach(item => {
  Mock.mock(
    "/mock" + item.url,
    item.method,
    (req: any): ResponseData => {
      // 判断是否在白名单中
      const flag = whiteList.includes(req.url)
      const { body } = req
      req.body = body ? JSON.parse(req.body) : undefined
      if (!flag) {
        const { valid, userId } = decodeToken(req.body.headers.token)
        if (valid) {
          req.body.userId = userId
        } else {
          return {
            code: 401,
            msg: "token已过期",
            success: false,
            data: null
          }
        }
      }
      return item.cb(req) as ResponseData
    })
})
